package io.feige.rpc.protocol.kryo;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBufferInputStream;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;

import com.esotericsoftware.kryo.Kryo; 
import com.esotericsoftware.kryo.io.Input;
  
public class ObjectKryoDecoder extends LengthFieldBasedFrameDecoder {
	
    public ObjectKryoDecoder() {  
        this(10485760);  
    }  
  
    public ObjectKryoDecoder(int maxObjectSize) {  
        super(maxObjectSize, 0, 4, 0, 4);  
    }  
      
    @Override  
    protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {  
        ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);  
        if (frame == null) {  
            return null;  
        } 
        Input input = null;  
        try {  
            input = new Input(new ChannelBufferInputStream(frame));
            Kryo kryo = new Kryo();
            return kryo.readClassAndObject(input);  
        } finally {  
            input.close();  
        }  
    }  
}  